package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xyz.hubery.domain.User;
import xyz.hubery.domain.UserWallet;
import xyz.hubery.feign.CoinServiceFeign;
import xyz.hubery.mapper.UserWalletMapper;
import xyz.hubery.service.UserService;
import xyz.hubery.service.UserWalletService;

@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService{


    @Autowired
    private CoinServiceFeign coinServiceFeign ;
    @Autowired
    private UserService userService ;

    @Override
    public List<UserWallet> getCoinAddress(Long userId, Long coinId) {
        List<UserWallet> userWallets = list(new LambdaQueryWrapper<UserWallet>().eq(UserWallet::getUserId, userId).eq(UserWallet::getCoinId, coinId));
        return userWallets;
    }

    @Override
    public boolean addUserWallet(UserWallet userWallet) {
        User user = userService.getById(userWallet.getUserId());
        if(user==null){
            throw new IllegalArgumentException("用户不存在") ;
        }
        // 校验支付密码
        checkPayPassword(user.getPaypassword(),userWallet.getPayPassword()) ;
        // 校验币种是否存在
        String coinName = coinServiceFeign.getCoinName(userWallet.getCoinId());
        if(coinName==null){
            throw new IllegalArgumentException("币种不存在") ;
        }
        userWallet.setCoinName(coinName);
        return save(userWallet) ;
    }

    private void checkPayPassword(String paypasswordDB, String payPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(!passwordEncoder.matches(payPassword,paypasswordDB)){
            throw new IllegalArgumentException("支付密码错误") ;
        }
    }

    @Override
    public boolean deleteUserWallet( Long addressId, Long payPassword) {
        UserWallet userWallet = getById(addressId);
        if(userWallet==null){
            throw new IllegalArgumentException("提币地址不存在") ;
        }
        // 校验支付密码
        User user = userService.getById(userWallet.getUserId());
        if(user==null){
            throw new IllegalArgumentException("用户不存在") ;
        }
        checkPayPassword(user.getPaypassword(),payPassword.toString()) ;
        // 删除提币地址
        return removeById(addressId) ;
    }
}
